// pages/registerShop/registerShop.js
import WXAPI from './../../wxApi/main'
import store from './../../utils/store'
import WxValidate from './../../utils/wxValidate'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 注册信息
    registInfo: {
      latitude: '', // 纬度
      longitude: '', // 经度
      address: '', // 	门店地址		true	
      businessLicense: '', // 		营业执照		true	
      id: '', // 		当前店铺编号,传参做修改,不传参做新增		false
      idCard: '', // 		身份证号		true	
      name: '', // 		店铺名称		true	
      phone: '', // 		电话
      idCardImg: '' //  身份证正反面
    },
    // 提示信息
    tips: {

    },
    imgBaseUrl: app.globalData.imgBaseUrl,
    imgList: [], // 图片
    idCardImgList: [], //身份证
    uploadIdCardImgList: [], //服务器上传返回的身份证
    businessLicenseList: [] // 营业执照
  },
  // 上传图片
  ChooseImage(e) {
    let shop = e.currentTarget.dataset.shop
    let self = this
    let registInfo = this.data.registInfo
    console.log(shop)
    wx.showLoading({
      title: '图片上传中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        // 显示图片
        if (shop == 'shop') {
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            })
          } else {
            this.setData({
              imgList: res.tempFilePaths
            })
          }
        } else if (shop == 'license') {
          if (this.data.businessLicenseList.length != 0) {
            this.setData({
              businessLicenseList: this.data.businessLicenseList.concat(res.tempFilePaths)
            })
          } else {
            this.setData({
              businessLicenseList: res.tempFilePaths
            })
          }
        } else {
          if (this.data.idCardImgList.length != 0) {
            this.setData({
              idCardImgList: this.data.idCardImgList.concat(res.tempFilePaths)
            })
          } else {
            this.setData({
              idCardImgList: res.tempFilePaths
            })
          }
        }
        // 上传图片
        WXAPI.upload({
          file: res.tempFilePaths[0]
        }).then(function (res) {
          wx.hideLoading()
          res = JSON.parse(res)
          if (res.code == 200) {
            if (shop == 'shop') {
              registInfo.img = res.data
              self.setData({
                registInfo: registInfo,
                noImg: ''
              })
            } else if (shop == 'license') {
              registInfo.businessLicense = res.data
              self.setData({
                registInfo: registInfo,
                noBus: ''
              })
            } else {
              self.data.uploadIdCardImgList.push(res.data)
              registInfo.idCardImg = self.data.uploadIdCardImgList.join(',')
              if (self.data.uploadIdCardImgList.length == 2) {
                self.setData({
                  registInfo: registInfo,
                  noIdCard: ''
                })
              }

            }
          } else {
            wx.showToast({
              title: '图片上传失败...',
              icon: 'none',
              duration: 3000
            })
          }
        }).catch(function (e) {
          console.log(e)
          wx.showToast({
            title: e.msg,
            icon: 'none'
          })
        })
      },
      fail: function (e) {
        wx.hideLoading()
      }
    });
  },
  // 查看图片
  ViewImage(e) {
    let tag=e.currentTarget.dataset.tag
    if(tag=='shop'){
      wx.previewImage({
        urls: this.data.imgList,
        current: e.currentTarget.dataset.url
      });
    }else if(tag=='license'){
      wx.previewImage({
        urls: this.data.businessLicenseList,
        current: e.currentTarget.dataset.url
      });
    }else{
      wx.previewImage({
        urls: this.data.idCardImgList,
        current: e.currentTarget.dataset.url
      });
    }
    
  },
  // 删除图片
  DelImg(e) {
    let shop = e.currentTarget.dataset.shop
    let registerShop = this.data.registInfo
    console.log(registerShop)
    wx.showModal({
      title: '删除提示',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          if (shop == 'shop') {
            this.data.imgList.splice(e.currentTarget.dataset.index, 1);
            registerShop.img = ''
            this.setData({
              imgList: this.data.imgList,
              registerShop: registerShop
            })
          } else if (shop == 'license') {
            this.data.businessLicenseList.splice(e.currentTarget.dataset.index, 1);
            registerShop.businessLicense = ''
            this.setData({
              businessLicenseList: this.data.businessLicenseList,
              registerShop: registerShop
            })
          } else {
            this.data.idCardImgList.splice(e.currentTarget.dataset.index, 1);
            let length = this.data.idCardImgList
            if (length != 0) {
              let array = []
              this.data.idCardImgList.forEach(element => {
                let img = element.substring(element.indexOf('img'))
                array.push()
                this.data.uploadIdCardImgList.push(img)
              })
              registerShop.idCardImg = array.join(',')
            } else {
              registerShop.idCardImg = ''
            }
            this.setData({
              idCardImgList: this.data.idCardImgList,
              registerShop: registerShop,
              uploadIdCardImgList: this.data.uploadIdCardImgList
            })
          }
        }
      }
    })
  },

  //获取位置
  getLocation(e) {
    var that = this
    let registInfo = this.data.registInfo
    wx.chooseLocation({
      success: function (res) {
        // console.log(res)
        registInfo.address = res.address
        registInfo.latitude = res.latitude
        registInfo.longitude = res.longitude
        that.setData({
          registInfo: registInfo
        })
      },
      fail: function (err) {
        if (err.errMsg == "chooseLocation:fail auth deny") {
          wx.showModal({
            title: '温馨提示',
            content: '亲，为了不影响您的正常使用，请同意授权',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    console.log(res.authSetting)
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },

  // 双向绑定
  inputedit: function (e) {
    // 1. input 和 info 双向数据绑定
    let dataset = e.currentTarget.dataset;
    //data-开头的是自定义属性，可以通过dataset获取到，dataset是一个json对象，有obj和item属性，可以通过这两个实现双向数据绑定，通过更改这两个值，对不同name的变量赋值
    let value = e.detail.value;
    this.data[dataset.obj][dataset.item] = value;
    this.setData({
      obj: this.data[dataset.obj]
    });
    if (value) {
      this.data[dataset.tips] = ''
      let tips = dataset.tips
      this.setData({
        [tips]: this.data[dataset.tips]
      });
    }
  },

  // 表单验证
  initValidate() {
    let rules = {
      address: {
        required: true
      },
      businessLicense: {
        required: true
      },
      idCardImg: {
        required: true
      },
      img: {
        required: true
      },
      name: {
        required: true,
      },
      // idCard: {
      //   required: true,
      //   idcard: true
      // },
      phone: {
        required: true,
        tel: true
      }
    }

    let message = {
      address: {
        required: '请选择或输入一个地址'
      },
      businessLicense: {
        required: '请上传营业执照'
      },
      idCardImg: {
        required: '请上传身份证正反面'
      },
      img: {
        required: '请上传店铺图片'
      },
      name: {
        required: '请输入姓名'
      },
      // idCard: {
      //   required: '请输入18位正确身份证号'
      // },
      phone: {
        required: '请输入11位正确电话号码'
      }
    }
    //实例化当前的验证规则和提示消息
    this.WxValidate = new WxValidate(rules, message);
  },

  // 注册
  registerShop(e) {
    let that = this
    let params = e.detail.value;
    console.log(this.data.registInfo)
    //表单元素验证不通过，此处给出相应提示
    if (!this.WxValidate.checkForm(params)) {
      let error = this.WxValidate.errorList;
      error.map(item => {
        switch (item.param) {
          case "address":
            //TODO
            that.setData({
              noAdd: item.msg
            })
            break;
          case "businessLicense":
            that.setData({
              noBus: item.msg
            })
            break;
          case "idCardImg":
            that.setData({
              noIdCard: item.msg
            })
            break;
          case "img":
            that.setData({
              noImg: item.msg
            })
            break;
          case "name":
            that.setData({
              noName: item.msg
            })
            break;
            // case "idCard":
            //   that.setData({
            //     noId: item.msg
            //   })
            //   break;
          case "phone":
            that.setData({
              noPhone: item.msg
            })
            break;
        }
      })
      return false;
    }
    if (this.data.registInfo.idCardImg.indexOf(',') == -1) {
      that.setData({
        noIdCard: '身份证信息不完整,请完善'
      })
      return false
    }
    // 表单验证通过
    WXAPI.registerShop(this.data.registInfo).then(function (res) {
      console.log(res)
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 3000
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/home',
          })
        }, 2000);
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 3000
        })
      }
    }).catch(function (e) {
      console.log(e)
      wx.showToast({
        title: e.msg,
        icon: 'none'
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate();
    let imgList = this.data.imgList
    let businessLicenseList = this.data.businessLicenseList
    let idCardImgList = this.data.idCardImgList
    if (options.id) {
      WXAPI.shopDetail({
        id: options.id
      }).then(res => {
        console.log(res)
        imgList.push(this.data.imgBaseUrl + res.data.img)
        businessLicenseList.push(this.data.imgBaseUrl + res.data.businessLicense)
        idCardImgList.push(this.data.imgBaseUrl + res.data.idCardImg.split(',')[0])
        idCardImgList.push(this.data.imgBaseUrl + res.data.idCardImg.split(',')[1])
        console.log(idCardImgList)
        if (res.code == 200) {
          this.setData({
            registInfo: res.data,
            imgList: imgList,
            businessLicenseList: businessLicenseList,
            idCardImgList: idCardImgList
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})